export class CodeArtsRepoError extends Error {
  constructor(
    message: string,
    public readonly status: number,
    public readonly response: unknown
  ) {
    super(message);
    this.name = "CodeArtsRepoError";
  }
}

export class CodeArtsRepoValidationError extends CodeArtsRepoError {
  constructor(message: string, status: number, response: unknown) {
    super(message, status, response);
    this.name = "CodeArtsRepoValidationError";
  }
}

export class CodeArtsRepoResourceNotFoundError extends CodeArtsRepoError {
  constructor(resource: string) {
    super(`资源未找到: ${resource}`, 404, { message: `${resource} 未找到` });
    this.name = "CodeArtsRepoResourceNotFoundError";
  }
}

export class CodeArtsRepoAuthenticationError extends CodeArtsRepoError {
  constructor(message = "认证失败") {
    super(message, 401, { message });
    this.name = "CodeArtsRepoAuthenticationError";
  }
}

export class CodeArtsRepoPermissionError extends CodeArtsRepoError {
  constructor(message = "权限不足") {
    super(message, 403, { message });
    this.name = "CodeArtsRepoPermissionError";
  }
}

export class CodeArtsRepoRateLimitError extends CodeArtsRepoError {
  constructor(
    message = "超出频率限制",
    public readonly resetAt: Date
  ) {
    super(message, 429, { message, reset_at: resetAt.toISOString() });
    this.name = "CodeArtsRepoRateLimitError";
  }
}

export class CodeArtsRepoConflictError extends CodeArtsRepoError {
  constructor(message: string) {
    super(message, 409, { message });
    this.name = "CodeArtsRepoConflictError";
  }
}

export function isCodeArtsRepoError(error: unknown): error is CodeArtsRepoError {
  return error instanceof CodeArtsRepoError;
}

export function createCodeArtsRepoError(status: number, response: any): CodeArtsRepoError {
  switch (status) {
    case 401:
      return new CodeArtsRepoAuthenticationError(response?.message);
    case 403:
      return new CodeArtsRepoPermissionError(response?.message);
    case 404:
      return new CodeArtsRepoResourceNotFoundError(response?.message || "资源");
    case 409:
      return new CodeArtsRepoConflictError(response?.message || "发生冲突");
    case 422:
      return new CodeArtsRepoValidationError(
        response?.message || "验证失败",
        status,
        response
      );
    case 429:
      return new CodeArtsRepoRateLimitError(
        response?.message,
        new Date(response?.reset_at || Date.now() + 60000)
      );
    default:
      return new CodeArtsRepoError(
        response?.message || "CodeArtsRepo API错误",
        status,
        response
      );
  }
} 